import { Link } from '@@/exports';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { message } from 'antd';
import { useNavigate } from 'umi';
import styles from '@/global.less';
import { userLoginUsingPost } from '@/services/backend/userController';
import Footer from '@/components/Footer';
import React from 'react';

/**
 * 用户注册页面
 */
const Register: React.FC = () => {
  const navigate = useNavigate();

  /**
   * 用户注册
   * @param fields
   */
  const handleUserRegister = async (fields: API.UserRegisterRequest) => {
    const hide = message.loading('注册中');
    try {
      await userLoginUsingPost({ ...fields });
      hide();
      message.success('注册成功');
      navigate('/user/login', {
        replace: true,
      });
    } catch (e: any) {
      hide();
      message.error('注册失败，' + e.message);
    }
  };

  return (
    <div className={styles.container}>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm<API.UserRegisterRequest>
          title="注册页面"
          subTitle="快速注册账号"
          submitter={{
            searchConfig: {
              submitText: '注册',
            },
          }}
          onFinish={async (formData) => {
            await handleUserRegister(formData);
          }}
        >
          <>
            <ProFormText
              name="userName"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined className={'prefixIcon'} />,
              }}
              placeholder={'请输入用户名'}
              rules={[
                {
                  required: true,
                  message: '请输入用户名!',
                },
              ]}
            />
            <ProFormText
              name="userAccount"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined className={'prefixIcon'} />,
              }}
              placeholder={'请输入账号（至少 4 位）'}
              rules={[
                {
                  required: true,
                  message: '请输入账号!',
                },
              ]}
            />
            <ProFormText.Password
              name="userPassword"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={'prefixIcon'} />,
              }}
              placeholder={'请输入密码（至少 6 位）'}
              rules={[
                {
                  required: true,
                  message: '请输入密码！',
                },
              ]}
            />
          </>
          <div
            style={{
              marginBottom: 24,
            }}
          >
            <Link to="/user/login">老用户登录</Link>
          </div>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};
export default Register;
